/**
 * SharedPreferenceUtil.java
 */
package com.krui.iweibo.utils;

import java.io.UnsupportedEncodingException;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.media.FaceDetector.Face;
import android.util.Xml.Encoding;

import com.krui.iweibo.model.UserInfo;

/**
 * SharedPreferenceUtil.java
 * @author krui
 * 2012-6-27 上午05:06:29
 * 
 */
public class SharedPreferenceUtil {
	
	public static final String LOGIN_USER = "login_user";
	
	
	/**
	 * 保存当前登录用户
	 * @param context
	 * @param userInfo
	 */
	public static void savaLoginUser(Context context,UserInfo userInfo){
		SharedPreferences sp =context.getSharedPreferences(LOGIN_USER, Context.MODE_PRIVATE);
		
		Editor editor = sp.edit();
		
		editor.putString("userId", userInfo.getUserId());
		editor.putString("userName", userInfo.getUserName());
		editor.putString("token", userInfo.getToken());
		editor.putString("tokenSecert", userInfo.getTokenSecret());
		if (userInfo.getUserIcon() != null) {
			try {
				editor.putString("userIcon", new String(ImageFactory.Bitmap2Bytes(userInfo.getUserIcon()),"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			editor.putString("loginTime", userInfo.getLoginTime());
		}
		
		editor.commit();
	}
	
	
	/**
	 * 得到当前登录用户
	 * @param context
	 * @return
	 */
	public static UserInfo getLoginUser(Context context){
		SharedPreferences sp =context.getSharedPreferences(LOGIN_USER, Context.MODE_PRIVATE);
		
		String userId = sp.getString("userId", "");//""表示如果userId不存在的话就返回""，这个""是默认返回值
		String userName = sp.getString("userName", "");
		String token = sp.getString("token", "");
		String tokenSecret = sp.getString("tokenSecert", "");
		String tempIcon = sp.getString("userIcon", "");
		byte[] byteIcon = tempIcon.getBytes();
		Bitmap userIcon = ImageFactory.Bytes2Bimap(byteIcon);
		String loginTime = sp.getString("loginTime","");
		
		
		if ("".equals(userId)) {
			return null;
		}
		
		UserInfo userInfo = new UserInfo(userId, userName, token, tokenSecret, "1", userIcon, loginTime);
		return userInfo;
	}

}
